package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Cagelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    private Map<String,Object> cache = new HashMap<>();

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成父子的树形结构
        //    1）找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{

            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort() == null ? 0: menu1.getSort()) - (menu2.getSort() == null ? 0: menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPah(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 每一个需要缓存的数据，都要指定放到哪个名字的缓存 【缓存的分区（按照业务类型）】
     * @return
     */
    //
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)  //代表当前方法的结果需要缓存，如果缓存中有，方法不用调用，如果缓存中没有，会调用方法，最后将方法的结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys......");
        long start = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        System.out.println("消耗时间：" + (System.currentTimeMillis() - start));
        return categoryEntities;
    }

    //从数据库查询并封装分类数据 io.netty.util.internal.OutOfDirectMemoryError: failed to allocate
    //springboot2.0以后默认使用lettuce操作redis的客户端，它使用netty进行网络通信
    //lettuce的bug导致netty堆处内存溢出-Xmx300m;netty如果没有指定堆外内存，默认使用-Xmx300m
//    可以通过-Dio.netty.maxDirectMemory进行设置
    //解决方案：不能使用-Dio.netty.maxDirectMemory只支调大堆外内存由于lettuce没有及时释放内存
//    //1。升级lettuce客户端（但新版本还没解决这个问题）2）切换使用jedis



    @Override
    public Map<String, List<Cagelog2Vo>> getCatelogJson() {
        //给缓存中放json字符串，拿出的json字符串，还要逆转为能的对象类型  序列化，反序列化
        //1、加入缓存逻辑，缓存中存的数据是json字符串
        //JSON跨语言，跨平台兼容
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间(加随机值)：解愉缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            //缓存中没有，查询数据库
            System.out.println("getCatelogJson---缓存中不命中，将要查询数据库");
            Map<String, List<Cagelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedisLock();

            return catelogJsonFromDb;
        }
        System.out.println("getCatelogJson---缓存中命中");
        Map<String, List<Cagelog2Vo>> result = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Cagelog2Vo>>>(){});
        return result;
    }


    /**
     * 分布式锁
     * 缓存里的数据如何和数据库保持一致
     * 缓存数据一致性问题 cacal  Canal(redis与mysql数据一致性)
     *
     * 1、canal server端会伪装成mysql从节点，去读取mysql主节点binlog文件，实现增量同步
     *
     * 2、canal server端将数据以json格式同步到客户端，MQ消费者消费消息，将数据同步到redis
     *
     * @return
     *
     */

    public Map<String, List<Cagelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {

        //占分布式锁。
        //1.锁的名字，锁的粒度，越细越快
        //锁的粒度：具体缓存的是某个数据，11-号商品：produc-11-lock   puduct-12-lock
        RLock lock = redisson.getLock("catelogJson-lock");
        lock.lock();
        Map<String, List<Cagelog2Vo>> dataFromDb;
        try{
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock();
        }
        return getDataFromDb();

    }

    public Map<String, List<Cagelog2Vo>> getCatelogJsonFromDbWithRedisLock() {

        //占分布式锁。去redis占坑 加锁和设置过期时间原子操作
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if(lock){
            System.out.println("获取分布式锁成功......");
            //加锁成功 ... 执行业务
            Map<String, List<Cagelog2Vo>> dataFromDb;
            try{
                dataFromDb = getDataFromDb();
            }finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //删除锁原子操
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock", uuid));
            }

//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)){
//                //删除自己的锁
//                redisTemplate.delete("lock");//删除锁
//            }
            //return getDataFromDb();
            return dataFromDb;
        }else{
            //加锁失败。。。重试
            //休眠100ms重试
            System.out.println("获取分布式锁失败......");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromDbWithRedisLock();//自旋的方式

        }

    }

    private Map<String, List<Cagelog2Vo>> getDataFromDb() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(!StringUtils.isEmpty(catalogJson)){
            Map<String, List<Cagelog2Vo>> result = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Cagelog2Vo>>>(){});
            return result;
        }
        System.out.println("getCatelogJsonFromDb---查询了数据库");

        List<CategoryEntity> selectList = baseMapper.selectList(null);


        List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
        //2、封状数据
        Map<String, List<Cagelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k ->k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个一级分的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList,v.getCatId());
            //2、封装上面的结果
            List<Cagelog2Vo> cagelog2Vos = null;
            if (categoryEntities != null) {
                cagelog2Vos = categoryEntities.stream().map(l2 -> {
                    Cagelog2Vo cagelog2Vo = new Cagelog2Vo(v.getCatId().toString(), null,
                            l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList,l2.getCatId());
                    if(level3Catelog != null){
                        List<Object> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Cagelog2Vo.Catelog3Vo catelog3Vo = new Cagelog2Vo.Catelog3Vo(l2.getCatId().toString(),
                                    l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        cagelog2Vo.setCatalog3List(collect);
                    }
                    return cagelog2Vo;
                }).collect(Collectors.toList());
            }
            return cagelog2Vos;
        }));
        String jsonString = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJson",jsonString,1,TimeUnit.DAYS);
        return parent_cid;
    }

    public Map<String, List<Cagelog2Vo>> getCatelogJsonFromDbWithLocalLock() {

//        Map<String,List<Cagelog2Vo>> catalogJson = (Map<String, List<Cagelog2Vo>>) cache.get("catalogJson");
//        if(catalogJson == null){
//            cache.put("catalogJson",parent_cid);
//        }
//        return catalogJson;
        /**
         * 只要是同一把锁，就能锁住需要这个锁的所有线程
         * 1.synchronized (this):springboot所有的组件在容器中都是单例的
         * 2.本地锁，synchronized，JUC（lock）,在分布式情况下，必须有分布式锁
         */
        synchronized (this){
            //得到锁以后，我们应该再去缓存中确定一次，如果没有才需要继续查询
            return getDataFromDb();
        }


    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());
        return collect;
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    //递归查所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> childrens = all.stream().filter((categoryEntity) -> {
            return (categoryEntity.getParentCid().longValue() == root.getCatId().longValue());
        }).map(categoryEntity -> {
            //找子菜单
            if(categoryEntity.getCatId() == 164){
                System.out.println("root.getCatId()...."+categoryEntity.getCatId());
            }
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //菜单排序
            return (menu1.getSort() == null ? 0: menu1.getSort()) - (menu2.getSort() == null ? 0: menu2.getSort());
        }).collect(Collectors.toList());
        return childrens;
    }

}